package com.jingdun.sport.api.controller;

import com.alipay.api.internal.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jingdun.sport.bean.model.*;
import com.jingdun.sport.common.util.PageParam;
import com.jingdun.sport.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/sport/trend/")
@Api(tags = "动态详情")
public class TrendsController {

    @Autowired
    private TrendsService trendsService;

    @Autowired
    private TrendsChatService trendsChatService;

    @Autowired
    private TrendsSupportsService trendsSupportsService;

    @Autowired
    private TrendsPicsService trendsPicsService;

    @Autowired
    TrendsFollowService trendsFollowService;

    @Autowired
    TzUserFanService tzUserFanService;

    @Autowired
    UserService userService;

    /**
     * 获取动态明细
     *
     * @param trendsId 动态id
     * @param userId   自己，不是动态发布者的id
     * @return
     */
    @GetMapping("trendsDetail")
    @ApiOperation(value = "获取动态明细", notes = "获取动态明细")
    public ResponseEntity addTrendsChat(@RequestParam Long trendsId, @RequestParam String userId) {
//        userId为空代表用户未登录，关注内容为空
        if (userId == null) {
            return ResponseEntity.ok().build();
        }
        Trends trends = trendsService.getById(trendsId);
        if (userId != null) {
            LambdaQueryWrapper<TrendsFollow> trendsFollowLambdaQueryWrapper = new LambdaQueryWrapper<TrendsFollow>()
                    .eq(TrendsFollow::getTrendsId, trendsId).eq(TrendsFollow::getUserId, userId);
            int followCount = trendsFollowService.count(trendsFollowLambdaQueryWrapper);
            trends.setIsFollow(followCount > 0);
        } else {
            trends.setIsFollow(false);
        }
        QueryWrapper<TzUserFan> wrap = new QueryWrapper<>();
        wrap.eq("user_id", userId).eq("be_fan_user_id", trends.getUserId());
        TzUserFan uf = tzUserFanService.getOne(wrap);
        trends.setIsFollow(uf != null && uf.isEnable());

        LambdaQueryWrapper<TrendsChat> trendsChatLambdaQueryWrapper = new LambdaQueryWrapper<TrendsChat>()
                .eq(TrendsChat::getTrendsId, trendsId);
        int chartCount = trendsChatService.count(trendsChatLambdaQueryWrapper);
        trends.setChatCount(chartCount);

        LambdaQueryWrapper<TrendsSupports> trendsSupportsLambdaQueryWrapper = new LambdaQueryWrapper<TrendsSupports>()
                .eq(TrendsSupports::getTrendsId, trendsId);
        int supportCount = trendsSupportsService.count(trendsSupportsLambdaQueryWrapper);
        trends.setSupportCount(supportCount);

        LambdaQueryWrapper<TrendsSupports> trendsSupportsLambdaQueryWrapperNew = new LambdaQueryWrapper<TrendsSupports>()
                .eq(TrendsSupports::getTrendsId, trendsId).eq(TrendsSupports::getUserId, userId);
        TrendsSupports trendsSupports = trendsSupportsService.getOne(trendsSupportsLambdaQueryWrapperNew);
        trends.setHasSupport(trendsSupports != null && trendsSupports.getEnable() == 1);

        LambdaQueryWrapper<TrendsPics> trendsPicsLambdaQueryWrapper = new LambdaQueryWrapper<TrendsPics>()
                .eq(TrendsPics::getTrendsId, trendsId);
        List<TrendsPics> trendsPicsList = trendsPicsService.list(trendsPicsLambdaQueryWrapper);
        for (TrendsPics trendsPics : trendsPicsList) {
            if (StringUtils.isEmpty(trends.getPic())) {
                trends.setPic(trendsPics.getPicUrl());
            } else {
                trends.setPic(trends.getPic() + ";" + trendsPics.getPicUrl());
            }
        }
        User user = userService.getById(trends.getUserId());
        trends.setLogo(user.getPic());
        trends.setNickName(user.getNickName());
        return ResponseEntity.ok(trends);
    }

    @GetMapping("listAllTrends")
    @ApiOperation(value = "获取动态列表", notes = "获取动态列表")
    public ResponseEntity listAllTrends(@RequestParam String uId, PageParam pageParam, @RequestParam Integer type) {
        ApiResult apiResult = ApiResult.getInstance();
        QueryWrapper<Trends> twrap = new QueryWrapper<>();
        twrap.eq("enable", 1).orderByDesc("gmt_create");
        if (type != null) {
            twrap.eq("type", type);
        }
        IPage<Trends> page = new Page<>();
        BeanUtils.copyProperties(pageParam, page);
        IPage<Trends> trendsIPage = trendsService.page(page, twrap);
        List<Trends> allTrends = trendsIPage.getRecords();
        for (int i = 0; i < allTrends.size(); i++) {
            Trends trends = allTrends.get(i);
            String uid = trends.getUserId();
            QueryWrapper<User> uwrap = new QueryWrapper<>();
            uwrap.eq("user_id", uid);
            User u = userService.getOne(uwrap);
            if (u != null) {
                trends.setLogo(u.getPic());
                trends.setNickName(u.getNickName());
                //如果当前用户关注了该动态的用户，标记状态
                QueryWrapper<TzUserFan> ufwrap = new QueryWrapper<>();
                ufwrap.eq("user_id", uId).eq("be_fan_user_id", trends.getUserId()).eq("enable", "1");
                int c = tzUserFanService.count(ufwrap);
                if (c > 0) {
                    trends.setIsFollow(true);
                } else {
                    trends.setIsFollow(false);
                }
//                评论总数
                QueryWrapper<TrendsChat> trendsChatQueryWrapper = new QueryWrapper<>();
                trendsChatQueryWrapper.eq("trends_id", trends.getId());
                int chatCount = trendsChatService.count(trendsChatQueryWrapper);
                trends.setChatCount(chatCount);
//                点赞总数
                QueryWrapper<TrendsSupports> trendsSupportsQueryWrapper = new QueryWrapper<>();
                trendsSupportsQueryWrapper.eq("trends_id", trends.getId());
                int allSupportcount = trendsSupportsService.count(trendsSupportsQueryWrapper);
                trends.setSupportCount(allSupportcount);
//                是否已经点赞过
                QueryWrapper<TrendsSupports> trendsHasSupport = new QueryWrapper<>();
                trendsHasSupport.eq("user_id", uId).eq("trends_id", trends.getId());
                int hasSupportCount = trendsSupportsService.count(trendsHasSupport);
                if (hasSupportCount > 0) {
                    trends.setHasSupport(true);
                } else {
                    trends.setHasSupport(false);
                }
//                图片列表
                QueryWrapper<TrendsPics> trendsPicsQueryWrapper = new QueryWrapper<>();
                trendsPicsQueryWrapper.eq("trends_id", trends.getId());
                List<TrendsPics> vls = trendsPicsService.list(trendsPicsQueryWrapper);
                List<String> pics = vls.stream().map(TrendsPics::getPicUrl).collect(Collectors.toList());
                trends.setPics(pics);
            }
        }
        apiResult.setData(trendsIPage);
        return ResponseEntity.ok(apiResult);
    }


    @PostMapping("deleteTrends")
    @ApiOperation(value = "删除动态", notes = "删除动态")
    public ResponseEntity listAllTrends(String userId, Long trendId) {
        Trends trends = trendsService.getById(trendId);
        if (trends.getClasses() == 1) {
            return ResponseEntity.ok(ApiResult.getInstance().setCode(201).setData("冒险动态不允许删除"));
        }
        LambdaUpdateWrapper<Trends> trendsLambdaUpdateWrapper = new LambdaUpdateWrapper<Trends>()
                .eq(Trends::getId, trendId)
                .eq(Trends::getUserId, userId)
                .set(Trends::getEnable, 0);
        trendsService.update(trendsLambdaUpdateWrapper);
        LambdaQueryWrapper<TrendsFollow> trendsFollowLambdaQueryWrapper = new LambdaQueryWrapper<TrendsFollow>()
                .eq(TrendsFollow::getTrendsId, trendId);
        trendsFollowService.remove(trendsFollowLambdaQueryWrapper);
        return ResponseEntity.ok(ApiResult.getInstance());
    }
}